package com.ccf.business.etl.controller;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.util.StrUtil;
import com.common.utils.constant.Constants;
import com.ccf.business.etl.model.vo.JobVO;
import com.ccf.business.etl.model.vo.ScheduleCountVO;
import com.ccf.business.etl.model.vo.TopTenCountVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.common.model.pojo.Query;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import com.ccf.business.etl.model.Job;
import com.ccf.business.etl.service.IJobService;
import com.common.model.result.PageResult;
import com.common.model.result.Result;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

/**
 * 任务运行实例表
 *
 * @author zhaoj
 * @date 2021-12-01 15:15:53
 */
@Slf4j
@RestController
@RequestMapping("/job")
@Api(tags = "任务运行实例表")
public class JobController {
    @Autowired
    private IJobService jobService;

    /**
     * 列表
     */
    @ApiOperation(value = "分页查询列表")
    @GetMapping
    public PageResult list(Query query) {
        return jobService.findList(query);
    }


    /**
     * 查询
     */
    @ApiOperation(value = "查询")
    @GetMapping("/{id}")
    public Result getById(@PathVariable String id) {
        JobVO model = jobService.detail(id);
        return Result.succeed(model, "查询成功");
    }

    /**
     * 新增or更新
     */
    @ApiOperation(value = "保存")
    @PostMapping
    public Result save(@RequestBody Job job) {
        jobService.saveOrUpdate(job);
        return Result.succeed("保存成功");
    }

    /**
     * 删除
     */
    @ApiOperation(value = "删除")
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable String id) {
        //批量删除
        if (StrUtil.contains(id, ",")){
            String[] ids = StrUtil.split(id, ",");
            jobService.removeByIds(Arrays.stream(ids).collect(Collectors.toList()));
        } else {
            jobService.removeById(id);
        }
        return Result.succeed("删除成功");
    }


    /**
     * 任务概览-统计任务运行情况
     */
    @ApiOperation(value = "任务概览-统计任务运行情况")
    @GetMapping("/running/count/{day}")
    public Result runningCountDay(@PathVariable String day) {
        List<ScheduleCountVO> scheduleCountVOS = jobService.runningCountDay(day);
        return Result.succeed(scheduleCountVOS,"查询成功");
    }

    /**
     * 任务概览统计-
     * 近30天作业实例执行时长排行TOP 10
     * 近30天作业实例运行失败TOP 10
     */
    @ApiOperation(value = "任务概览-用时统计TOP10")
    @GetMapping("/running/time/count/{status}")
    public Result runningTimeCountStatus(@PathVariable String status) {
        List<TopTenCountVO> topTenCountVOS = jobService.runningTimeCountStatus(status);
        return Result.succeed(topTenCountVOS,"查询成功");
    }

    /**
     * 下载日志
     */
    @ApiOperation(value = "下载日志")
    @GetMapping("/log/download/{id}")
    public void dwnloadLog(@PathVariable String id, HttpServletResponse response) throws IOException {
        JobVO job = jobService.detail(id);
        StringBuffer content = new StringBuffer();
        for (String log : job.getLogs()) {
            content.append(log + Constants.BR);
        }
        response.setContentType("text/plain");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("job.log", "UTF-8"));
        //输出到response中
        ServletOutputStream outputStream = response.getOutputStream();
        BufferedOutputStream buffer = new BufferedOutputStream(outputStream);
        buffer.write(content.toString().getBytes("UTF-8"));
        buffer.flush();
        buffer.close();
        outputStream.close();
    }
}
